package com.ljyh.cygnus.utils

import android.content.Context
import android.util.Log
import java.io.File
import android.os.Build
import java.io.FileOutputStream
import java.io.IOException

object FileUtils {
    // App私有目录中的目标文件名
    private const val SQLITE_BINARY_NAME = "sqlite3"

    fun getSqlite3Path(context: Context): String? {
        val appContext = context.applicationContext
        // 目标路径：/data/data/com.ljyh.cygnus/files/sqlite3
        val destFile = File(appContext.filesDir, SQLITE_BINARY_NAME)

        // 优化：如果文件已经存在，并且可执行，就直接返回路径
        if (destFile.exists() && destFile.canExecute()) {
            return destFile.absolutePath
        }

        try {
            // 根据设备的CPU架构，构建assets中的源文件路径
            val abi = Build.SUPPORTED_ABIS[0] // 获取首选ABI，例如 "arm64-v8a"
            val assetPath = "$abi/$SQLITE_BINARY_NAME"

            Log.d("FileUtils", "Copying sqlite3 from assets: $assetPath to ${destFile.absolutePath}")

            // 从assets中打开输入流
            appContext.assets.open(assetPath).use { inputStream ->
                // 创建到私有目录的输出流
                FileOutputStream(destFile).use { outputStream ->
                    // 复制文件
                    inputStream.copyTo(outputStream)
                }
            }

            // 最关键的一步：赋予文件执行权限
            if (destFile.setExecutable(true)) {
                Log.d("FileUtils", "sqlite3 copied and set to executable.")
                return destFile.absolutePath
            } else {
                Log.e("FileUtils", "Failed to set sqlite3 as executable.")
                return null
            }
        } catch (e: IOException) {
            Log.e("FileUtils", "Failed to copy sqlite3 from assets. Make sure the file exists for the device's ABI.", e)
            return null
        }
    }
}